import styles from './index.module.less';

import { exportLayout, updateLayout } from '@/api/layout';
import { Editor } from '@lle/d3-editor';
import { message } from '@/App';

interface IProps {
  editor: Editor;
  plHangNo: string;
}

export const ToolBar = (props: IProps) => {
  const { editor, plHangNo } = props;

  const onClickUndo = () => {
    editor.historyManager.undo();
  };

  const onClickRedo = () => {
    editor.historyManager.redo();
  };

  const onClickSave = async () => {
    const { content, parts, hangs } = editor.save();

    await updateLayout(plHangNo, content, parts, hangs);

    message.info('更新成功');
  };

  const onClickPreview = async () => {
    const { content, parts, hangs } = editor.save();

    await updateLayout(plHangNo, content, parts, hangs);

    window.open(`/preview?plHangNo=${plHangNo}`);
  };

  const onClickExport = async () => {
    const blob = await editor.export();

    const file = new File([blob], `挂组-${plHangNo}`);

    await exportLayout(plHangNo, file);

    message.info('导出成功');
  };

  return (
    <div className={styles.container}>
      <div className={styles.tool} title="撤销" onClick={onClickUndo}>
        <span className="iconfont icon-undo font24" />
      </div>
      <div className={styles.tool} title="恢复" onClick={onClickRedo}>
        <span className="iconfont icon-redo font24" />
      </div>
      <div className={styles.tool} title="保存" onClick={onClickSave}>
        <span className="iconfont icon-save font24" />
      </div>
      <div className={styles.tool} title="预览" onClick={onClickPreview}>
        <span className="iconfont icon-preview font24" />
      </div>
      <div className={styles.tool} title="导出" onClick={onClickExport}>
        <span className="iconfont icon-export font24" />
      </div>
    </div>
  );
};
